package com.textmanager.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

public class MainFrame extends JFrame {

    private boolean minimizeToTrayOnClose = true; // Added to control minimize to tray behavior

    private DirectoryTreePanel directoryTreePanel;
    private TextEditorPanel textEditorPanel;

    public MainFrame() {
        setTitle("猫咪快笔记");
        // Set application icon
        try {
            ImageIcon icon = new ImageIcon(getClass().getResource("/icons/logo2.png")); // Assuming logo2.png is in src/main/resources/icons
            if (icon.getImageLoadStatus() == MediaTracker.COMPLETE) {
                setIconImage(icon.getImage());
            } else {
                System.err.println("Could not load application icon. Make sure 'icons/logo2.png' is in the classpath.");
            }
        } catch (Exception e) {
            System.err.println("Error loading application icon: " + e.getMessage());
            e.printStackTrace();
        }

        // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Changed to handle minimize to tray
        setSize(1024, 768);
        setLocationRelativeTo(null); // Center the frame

        initComponents();
        layoutComponents();
        setupInteractions();
        createMenuBar(); // Add this line
        initTrayIcon(); // Add this line for system tray functionality
    }

    private void createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        JMenu helpMenu = new JMenu("帮助");
        JMenuItem aboutItem = new JMenuItem("关于");
        aboutItem.addActionListener(e -> showAboutDialog());
        helpMenu.add(aboutItem);

        JMenu settingsMenu = new JMenu("设置");
        JCheckBoxMenuItem minimizeToTrayItem = new JCheckBoxMenuItem("关闭时最小化到托盘", true);
        minimizeToTrayItem.addActionListener(e -> {
            minimizeToTrayOnClose = minimizeToTrayItem.isSelected();
        });
        settingsMenu.add(minimizeToTrayItem);

        menuBar.add(settingsMenu); // Add settings menu before help menu for conventional placement
        menuBar.add(helpMenu);
        setJMenuBar(menuBar);
    }

    private void showAboutDialog() {
        String aboutMessage = "\t\t\t\t猫咪快笔记 主要功能:\n" +
                "                - 树状目录管理笔记\n" +
                "                - 文本笔记编辑与保存\n" +
                "                - 支持插入图片和粘贴图片\n" +
                "                - 笔记内容搜索 文件名搜索\n" +
                "                - 右键快捷操作 (添加、修改、删除)\n" +
                "\n" +
                "                作者信息:\n" +
                "                一个热爱猫咪的程序员";
        JOptionPane.showMessageDialog(this, aboutMessage, "关于 猫咪快笔记", JOptionPane.INFORMATION_MESSAGE);
    }

    private void initComponents() {
        directoryTreePanel = new DirectoryTreePanel();
        textEditorPanel = new TextEditorPanel();
    }

    private void layoutComponents() {
        directoryTreePanel.setBorder(BorderFactory.createTitledBorder("文件目录"));
        textEditorPanel.setBorder(BorderFactory.createTitledBorder("笔记编辑区"));

        directoryTreePanel.setBackground(new Color(240, 240, 240)); // Light gray
        textEditorPanel.setBackground(new Color(220, 230, 240));    // Light blue-gray

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, directoryTreePanel, textEditorPanel);
        splitPane.setDividerLocation(300);
        splitPane.setResizeWeight(0.3); // Give 30% of extra space to the left panel when resizing
        add(splitPane, BorderLayout.CENTER);
    }

    private void setupInteractions() {
        // Connect the directory tree panel with the text editor panel
        directoryTreePanel.setTextEditorPanel(textEditorPanel);
        // After setup, try to load the first note
        directoryTreePanel.loadFirstNoteOnStartup(); 
    }

    private void initTrayIcon() {
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            return;
        }

        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon;
        final SystemTray tray = SystemTray.getSystemTray();

        // Load an image for the tray icon
        Image image = null;
        try {
            ImageIcon icon = new ImageIcon(getClass().getResource("/icons/logo2.png"));
            if (icon.getImageLoadStatus() == MediaTracker.COMPLETE) {
                image = icon.getImage();
            } else {
                System.err.println("Could not load tray icon image.");
            }
        } catch (Exception e) {
            System.err.println("Error loading tray icon image: " + e.getMessage());
        }
        if (image == null) { // Fallback if image loading failed
             // Create a default image if logo is not found
            image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = (Graphics2D) image.getGraphics();
            g2d.setColor(Color.BLUE);
            g2d.fillRect(0, 0, 16, 16);
            g2d.dispose();
        }


        trayIcon = new TrayIcon(image, "猫咪快笔记");
        trayIcon.setImageAutoSize(true);

        // Create a pop-up menu components
        MenuItem openItem = new MenuItem("打开");
        MenuItem exitItem = new MenuItem("退出");

        // Add components to pop-up menu
        popup.add(openItem);
        popup.addSeparator();
        popup.add(exitItem);

        trayIcon.setPopupMenu(popup);

        trayIcon.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1) { // Left click
                    setVisible(true);
                    setState(Frame.NORMAL);
                    tray.remove(trayIcon);
                }
            }
        });

        openItem.addActionListener(e -> {
            setVisible(true);
            setState(Frame.NORMAL);
            tray.remove(trayIcon);
        });

        exitItem.addActionListener(e -> {
            tray.remove(trayIcon);
            System.exit(0);
        });

        addWindowListener(new WindowAdapter() { // Corrected from addWindowStateListener to addWindowListener if that was a typo elsewhere, ensuring it's WindowListener for windowClosing
            @Override
            public void windowClosing(WindowEvent e) {
                System.out.println("windowClosing event triggered. minimizeToTrayOnClose: " + minimizeToTrayOnClose); // Debug print
                if (minimizeToTrayOnClose && SystemTray.isSupported()) {
                    try {
                        System.out.println("Attempting to add tray icon..."); // Debug print
                        tray.add(trayIcon);
                        System.out.println("Tray icon added. Attempting to hide window..."); // Debug print
                        setVisible(false);
                        System.out.println("Window hidden."); // Debug print
                    } catch (AWTException ex) {
                        System.err.println("AWTException: TrayIcon could not be added.");
                        ex.printStackTrace(); // Print stack trace for AWTException
                        System.exit(0); // Fallback to exit if tray fails
                    } catch (Throwable t) { // Catching Throwable to see any Error as well
                        System.err.println("Unexpected error or exception in windowClosing (minimizing to tray):");
                        t.printStackTrace();
                        // Attempt to hide even on other errors, then exit if that fails or is not appropriate
                        try {
                            setVisible(false);
                        } catch (Throwable t2) {
                            System.err.println("Failed to hide window during error handling (minimizing to tray):");
                            t2.printStackTrace();
                        }
                        // Consider if exiting here is the best strategy or if the app should remain in a hidden state
                        // For now, if tray add fails, we exit. If other error, we try to hide and then exit.
                        System.exit(1); // Exit with a different code to indicate error
                    }
                } else {
                    System.out.println("Exiting application directly.");
                    System.exit(0);
                }
            }
        });
        // Set default close operation to do nothing, as we handle it with windowClosing
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }
}